use super::Authenticator;
use async_trait::async_trait;
use std::collections::HashMap;
use std::net::SocketAddr;

pub struct UserPassAuthenticator {
    users: HashMap<String, String>,
}

impl UserPassAuthenticator {
    pub fn new(users: HashMap<String, String>) -> Self {
        let users = users
            .into_iter()
            .map(|(k, v)| (k.to_lowercase(), v))
            .collect();
        Self { users }
    }
}

#[async_trait]
impl Authenticator for UserPassAuthenticator {
    async fn authenticate(
        &self,
        _addr: SocketAddr,
        auth: &str,
        _tx: u64,
    ) -> anyhow::Result<(bool, String)> {
        let parts: Vec<&str> = auth.splitn(2, ':').collect();
        if parts.len() != 2 {
            return Ok((false, String::new()));
        }

        let username = parts[0].to_lowercase();
        let password = parts[1];

        if let Some(stored_pass) = self.users.get(&username) {
            if stored_pass == password {
                return Ok((true, username));
            }
        }

        Ok((false, String::new()))
    }
}
